﻿using System;
using System.Configuration;
using Data.implement;
using System.Collections.Generic;

namespace Data
{
    class UserRepositery : DataAccessBase<LYWebsiteSEntities1>, IUserRepositery
    {
        private static readonly log4net.ILog log =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public User GetOrInsertUser(WeiXinUser user, int? carType = null)
        {
            log.InfoFormat("UserRepositery.GetOrInsertUser(openId:{0} , name:({1})", user.openId, user.nickname);
            if (carType == 0)
                carType = null;
            User result = GetUser(user.openId);
            User returnValue;
            if (result == null || string.IsNullOrEmpty(result.UserName))
            {
                result = new User()
                {
                    UserName = user.nickname,
                    CarBatteryStatus = 0,
                    ChargingTimes = 0,
                    CreateDate = DateTime.Now,
                    CarId = carType,
                    GUID = Guid.NewGuid().ToString(),
                    LocationId = 1,
                    UpdateTime = carType == 0 ? (DateTime?) null : DateTime.Now,
                    OpenId = user.openId,
                    LimitTimes = 0,
                    city = user.city,
                    country = user.country,
                    headimgurl = user.headimgurl,
                    nickname = user.nickname,
                    province = user.province,
                    sex = user.sex
                };
                InsertRecord(result);
                ResetContext();
                returnValue = GetUser(result.UserId);

            }
            else
            {
                return result;
            }
            return returnValue;
        }

        public User SetUserCar(int userId, int carType)
        {
            log.InfoFormat("UserRepositery.SetUserCar({0} , ({1})", userId, carType);
            User user = GetUser(userId);
            user.CarId = carType;
            user.UpdateTime = DateTime.Now;
            UpdateRecord(user);
            ResetContext();
            User result = GetUser(userId);
            return result;
        }

        public bool AddChargingTime(int userId, int targetId)
        {
            log.InfoFormat("UserRepositery.AddChargingTime({0} , ({1})", userId, targetId);
            User target = GetUser(targetId);
            User user = GetUser(userId);

            if (target.ChargingTimes == null)
                target.ChargingTimes = 1;
            else
                target.ChargingTimes += 1; 

            if (user.LimitTimes == null)
                user.LimitTimes = 1;
            else
                user.LimitTimes += 1;

            int location = CheckLocation(target.ChargingTimes);
            if(location != 0)
                target.LocationId = location;

            UpdateRecord(target);
            return true;
        }

        public int CheckLocation(int? chargingTime)
        {
            log.InfoFormat("UserRepositery.CheckLocation({0})", chargingTime);
            string temp = ConfigurationSettings.AppSettings["limitlist"] as string;
            string[] numList = temp.Split(',');
            int index;
            for (index = 0; index < numList.Length; index++)
            {
                var num = numList[index];
                int location = int.Parse(num);
                if (chargingTime < location)
                {
                    return index + 1;
                    break;
                }
            }
            if (index == numList.Length)
                return index;
            return 0;
        }

        public User GetUser(string OpenId)
        {
            log.InfoFormat("UserRepositery.GetUser({0})", OpenId);
            User result = GetRecordByProperty<User>(d => d.OpenId == OpenId);
            return result;
        }

        public User GetUserByGuid(string Guid)
        {
            log.InfoFormat("UserRepositery.GetUserByGuid({0})", Guid);
            User result = GetRecordByProperty<User>(d => d.GUID == Guid);
            return result;
        }

        public bool DeleteUser(User entity)
        {
            log.InfoFormat("UserRepositery.DeleteUser({0})", entity.OpenId);
            var result = GetUser(entity.UserId);
            return DeleteRecord(result);
        }

        public User GetUser(int userId)
        {
            log.InfoFormat("UserRepositery.GetUser({0})", userId);
            User user = GetRecordByProperty<User>(d => d.UserId == userId);
            return user;
        }

        public List<User> GetTopChargingUsers(int Limit)
        {
            List<User> result = null;
            try
            {
                result = GetRecordsByProperty<User,int?>(d => d.ChargingTimes, Limit, true);
            }
            catch(Exception e)
            {
                log.ErrorFormat("UserRepositery.GetUsers(limit), {0}", e);
                result = null;
            }
            return result;
        }
    }
}